package lu.med.praxiswahl.wahlumed.dao.beans;

import java.util.List;
import javax.ejb.Local;
import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import lu.med.praxiswahl.wahlumed.dao.beans.daointerface.ReminderDAOInt;
import lu.med.praxiswahl.wahlumed.model.beans.CustomerTBL;
import lu.med.praxiswahl.wahlumed.model.beans.HonorarTBL;
import lu.med.praxiswahl.wahlumed.model.beans.RemindersTBL;

/**
 * Session Bean implementation class ReminderDAO
 */
@Stateless
@Local({ReminderDAOInt.class})
public class ReminderDAO implements ReminderDAOInt {

	
	@PersistenceContext(unitName = "gynaekomedic-ejbPU")
	private EntityManager	em	= null;
	
    /**
     * Default constructor. 
     */
    public ReminderDAO() 
    {
        
    }

	@Override
	public void delete(Long id) 
	{
		
		RemindersTBL item = this.retrieveReminderItemByID(id);

		CustomerTBL cust = item.getCustomer();

		cust.getRemindersItem().remove(item);

		em.remove(item);
		em.flush();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<RemindersTBL> findActualReminders() {
		try
		{
			return (List<RemindersTBL>) em.createQuery(
					"select r from RemindersTBL r where r.archivieren = false order by r.rechnung.erstell_datum desc"
					).getResultList();
		}
		catch (Exception e)
		{
			return null;
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<RemindersTBL> findOLDRemindersOfINTERVAL(String fromDatum, String toDatum) {
		try
		{
			return (List<RemindersTBL>) em.createQuery(
					"SELECT r FROM RemindersTBL r where  STR_TO_DATE(r.firstReminder,'%d.%m.%Y') between "
					+"STR_TO_DATE('"+fromDatum+"','%d.%m.%Y') and  STR_TO_DATE('"+toDatum+"','%d.%m.%Y') order by r.customer.nachname_1 asc").getResultList();
		}
		catch (Exception e)
		{
			return null;
		}
	}

	@Override
	public void persist(RemindersTBL todo) {
		em.persist(todo);
		em.flush();
		
	}

	@Override
	public void update(RemindersTBL todo) {
		em.merge(todo);
		em.flush();
		
	}

	@Override
	public RemindersTBL retrieveReminderItemByID(Long id) {
		return em.find(RemindersTBL.class, id);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<HonorarTBL> listUeberfaelligeRechnungen() {
		
		try
		{
			return (List<HonorarTBL>) em.createQuery(
					
					"SELECT h FROM HonorarTBL h where (DATE_FORMAT(curdate(), '%Y%m%d') - DATE_FORMAT(h.erstell_datum, '%Y%m%d')) >= 14"
					+" and h.bezahlt = false and h.imDossier = false  order by h.erstell_datum desc").getResultList();
		}
		catch (Exception e)
		{
			return null;
		}
	}

}
